"""
Web管理界面路由
"""

from fastapi import APIRouter, Request, Depends
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session

from ..core.database import get_db, HotTrend, GeneratedContent, PublishRecord

router = APIRouter()
templates = Jinja2Templates(directory="src/web/templates")


@router.get("/", response_class=HTMLResponse, summary="管理首页")
async def admin_dashboard(request: Request, db: Session = Depends(get_db)):
    """管理界面首页"""
    
    # 获取统计数据
    trends_count = db.query(HotTrend).count()
    contents_count = db.query(GeneratedContent).count()
    published_count = db.query(PublishRecord).filter(
        PublishRecord.status == "success"
    ).count()
    
    # 最新热点
    latest_trends = db.query(HotTrend).order_by(
        HotTrend.created_at.desc()
    ).limit(5).all()
    
    # 最新内容
    latest_contents = db.query(GeneratedContent).order_by(
        GeneratedContent.created_at.desc()
    ).limit(5).all()
    
    return templates.TemplateResponse("dashboard.html", {
        "request": request,
        "stats": {
            "trends_count": trends_count,
            "contents_count": contents_count,
            "published_count": published_count
        },
        "latest_trends": latest_trends,
        "latest_contents": latest_contents
    })


@router.get("/trends", response_class=HTMLResponse, summary="热点管理")
async def trends_page(request: Request, db: Session = Depends(get_db)):
    """热点管理页面"""
    
    trends = db.query(HotTrend).order_by(
        HotTrend.created_at.desc()
    ).limit(50).all()
    
    return templates.TemplateResponse("trends.html", {
        "request": request,
        "trends": trends
    })


@router.get("/contents", response_class=HTMLResponse, summary="内容管理")
async def contents_page(request: Request, db: Session = Depends(get_db)):
    """内容管理页面"""
    
    contents = db.query(GeneratedContent).order_by(
        GeneratedContent.created_at.desc()
    ).limit(50).all()
    
    return templates.TemplateResponse("contents.html", {
        "request": request,
        "contents": contents
    })


@router.get("/publish", response_class=HTMLResponse, summary="发布管理")
async def publish_page(request: Request, db: Session = Depends(get_db)):
    """发布管理页面"""
    
    records = db.query(PublishRecord).order_by(
        PublishRecord.created_at.desc()
    ).limit(50).all()
    
    return templates.TemplateResponse("publish.html", {
        "request": request,
        "records": records
    })


@router.get("/tasks", response_class=HTMLResponse, summary="任务管理")
async def tasks_page(request: Request):
    """任务管理页面"""
    
    return templates.TemplateResponse("tasks.html", {
        "request": request
    })